package classpath

import (
	"os"
	"path/filepath"
)

type Classpath struct {
	bootClasspath Entry //启动类路径
	extClasspath  Entry //扩展类路径
	userClasspath Entry
}

func (classpath *Classpath) readClass(classname string) ([]byte, Entry, error) {
	classname = classname +".class"
	if data,entry,err :=classpath.bootClasspath.readClass(classname);err ==nil{
		return data,entry,nil
	}
	if data,entry,err :=classpath.extClasspath.readClass(classname);err ==nil{
		return data,entry,err
	}
	return classpath.userClasspath.readClass(classname)
}

func (classpath *Classpath) String() string {
	return classpath.userClasspath.String()
}

func (classpath *Classpath) parseBootAndExtClasspath(jreOptions string) {
	jreDir := getJreDir(jreOptions)
	// jre/lib/*
	jreLibPath := filepath.Join(jreDir, "lib", "*")
	classpath.bootClasspath = newWildcardEntry(jreLibPath)
	// jre/lib/ext/*
	jreExtPath := filepath.Join(jreDir, "lib", "ext", "*")
	classpath.extClasspath = newWildcardEntry(jreExtPath)
}

func (classpath *Classpath) parseUserClasspath(cpOptions string) {
	if cpOptions == "" {
		cpOptions = "."
	}
	classpath.userClasspath = newEntry(cpOptions)
}



func getJreDir(jreOptions string) string {
	if jreOptions !="" && exists(jreOptions) {
		return jreOptions
	}
	if exists("./jre") {
		return "./jre"
	}
	if jh:=os.Getenv("JAVA_HOME"); jh!=""{
		return filepath.Join(jh,"jre")
	}
	panic("Can not find jre folder!")
}

func exists(path string) bool {
	if _,err := os.Stat(path); err == nil {
		if os.IsNotExist(err) {
			return false
		}
	}
	return true
}

func Parse(jreOptions, cpOptions string) *Classpath {
	cp := &Classpath{}
	cp.parseBootAndExtClasspath(jreOptions)
	cp.parseUserClasspath(cpOptions)
	return cp
}
